import { axios } from "@/plugins/axios";
import User from "../../models/user";
import * as types from "./mutation_types";

const actions = {
  async getUserInfo({ commit, state }, force=false) {
    if (state.isCurrentUserFetched !=null && !force) {
      await state.isCurrentUserFetched
      return state.currentUser
    } else {
      const waitableFetch = new Promise((resolve) => {
        this.currentUserResolver = resolve      
      });
      commit('setCurrentUserFetchPromise', waitableFetch);
      const user = await User.getCurrentUser()
      
      commit(types.CURRENT_USER_UPDATE, user);
      this.currentUserResolver(true)   
      return state.currentUser;
    }
  },
  getUserList({ commit, state }, active) {
    // commit(types.CUREENT_USER_GET_ERROR, null);
    const url = process.env.VUE_APP_API_URL + "api/v1/users";
    if (state.isUserListFetched) {
      return state.isUserListFetched.then(_=>{
        return state.userList
      })
    } else {
      const waitableFetch = new Promise((resolve) => {
        this.userlistResolver = resolve      
      });
      commit('setUserListFetchPromise', waitableFetch);

      const params = {
        per_page: 0,
      }
			if (active) {
				params.active = active;
			}
      return axios
        .get(url, { params: params })
        .then((res) => {
          let userList = []
          res.data.results.forEach((item) => {
            let user = Object.assign(new User(), item)
            userList.push(user)
          })
          const list = userList
            .filter((x) => x.type != "A")
            .sort((a, b) => a.username - b.username)
          this.userlistResolver(true)
          commit(types.CURRENT_USER_List_UPDATE, list)
          return list
        })
        .catch((e) => {
          commit(types.CUREENT_USER_GET_ERROR, "failed to fetch current user")
          return []
        })
    }
  },

  getSignImageList({ commit }) {
    const url = process.env.VUE_APP_API_URL + "api/sign_image";
    return axios.get(url).then((res) => {
      let sign_image_list = Array();
      res.data.forEach((x) => {
        let item = new SignImage();
        item = Object.assign(item, x);
        sign_image_list.push(item);
      });
      return sign_image_list;
    });
  },

  uploadSignImage({ commit }, image) {
    const url = process.env.VUE_APP_API_URL + "api/sign_image";
    return axios.post(url, { image: image });
  },

  deleteSignImage({ commit }, id) {
    const url = process.env.VUE_APP_API_URL + "api/sign_image/" + id;
    return axios.delete(url);
  },

  verifyPrivkey({ commit }, keypass) {
    const url = process.env.VUE_APP_API_URL + "api/privkey";
    return axios
      .get(url, { params: { keypass: keypass } })
      .then((res) => {
        return true;
      })
      .catch((e) => {
        return false;
      });
  },

  createPrivkey({ commit }, keypass) {
    const url = process.env.VUE_APP_API_URL + "api/privkey";
    const web_args = {
      keypass: keypass,
      is_server_create: true,
    };
    return axios.post(url, null, { params: web_args });
  },
};

function initialState() {
  return {
    currentUser: new User(),
    isCurrentUserFetched: null, // 变成一个返回当前用户的Promise
    userList: [],
    isUserListFetched: false
  };
}

const state = initialState();

const getters = {};

const mutations = {
  setCurrentUserFetchPromise(state, waitableFetch) {
    state.isCurrentUserFetched = waitableFetch
  },
  setUserListFetchPromise(state, waitableFetch){
    state.isUserListFetched = waitableFetch
  },
  [types.CURRENT_USER_UPDATE](state, userInfo) {
    state.currentUser = userInfo;
  },
  [types.CURRENT_USER_RESET](state) {
    state.currentUser = null;
    state.isUserListFetched = null
    const s = initialState();
    Object.keys(s).forEach((key) => {
      state[key] = s[key];
    });
  },
  [types.CUREENT_USER_GET_ERROR](state) {
    state.currentUser = null;
    const s = initialState();
    Object.keys(s).forEach((key) => {
      state[key] = s[key];
    });
  },
  [types.CURRENT_USER_List_UPDATE](state, userlist) {
    state.userList = userlist;
  },
  [types.CURRENT_USER_List_RESET](state) {
    state.userList = null;
    state.isUserListFetched = null
    const s = initialState();
    Object.keys(s).forEach((key) => {
      state[key] = s[key];
    });
  },
};

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations,
};
